'''Analyze Quintara Sequencing output .ab1 files
	Conventions: Samples are S#.N, where # is a construct, N is a clone
	WishList: Output: MUSCLE alignments of reads, +/- per clone, explanation of issues.'''

from Bio import Seq,SeqRecord,SeqIO,Align,AlignIO
from Bio.Align.Applications import MuscleCommandline
import csv
import datetime
import os
import pdb
import sys
		
def today():
    '''YYYY-MM-DD time to MMDDYY'''	
    date_str = str(datetime.datetime.today())
    return date_str[5:7]+date_str[8:10]+date_str[2:4]

def move_downloads(seq_dir):
    '''Extract all quintara .ab1 files from .zip archives to Sequencing directory'''      
    downloads_dir = '../../../../Downloads/'
    files = os.listdir(downloads_dir)
    files = [ filename for i, filename in enumerate(files) if filename.endswith('.zip') ]        
    for filename in files:
        #Unzip: if overwriting files, system will prompt. (Type A for overwrite All)
        os.system('unzip '+'"'+downloads_dir+filename+'"'+' "*.ab[i1]" -d '+seq_dir)
    return files

def parse_construct(seq_dir,sample_path,sample_id,phred,minLength):
    '''Construct to new FASTA Collection to align'''
    
    def add_samples():
        '''Add Sequencing Samples.
            Outputs: path to collection file'''
        seq_list_dir = seq_dir+in_id+'/'
        if not os.path.exists(seq_list_dir):
            os.mkdir(seq_list_dir)
        files = os.listdir(seq_dir)
        #Keep only .ab1 files
        files = [ filename for i, filename in enumerate(files) if filename.endswith('.ab1') ]
        for filename in files: 
            #Check for current sample_id (case-insensitive)
            if filename.upper().find(sample_id.upper())>-1:
                f = open(seq_dir+filename,'rb')
                seq_iter = SeqIO.AbiIO.AbiIterator(f,trim=phred)
                #Add Mott-trimmed sequence, P(error) < 0.05
                seq = seq_iter.next()
                if len(seq) > minLength:
                    seq_list.append(seq)
                f.close()
            for i,seq_record in enumerate(seq_list):
                if i==0:
                    ##########
                    #pdb.set_trace()
                    ##########	
                    #keep construct copy in genbank format for ApE display
                    if seq_record.name[-1] == '_':
                        seq_record.name = seq_record.name[0:-2]
                    SeqIO.write(seq_record,seq_list_dir+seq_record.id+'.gb','genbank')
                else:
                    SeqIO.write(seq_record,seq_list_dir+seq_record.name+'.fasta','fasta')
        print seq_list[0].id
        return seq_list
	
    in_id = sample_path.split('/')[-1].split('.')[0]
    seq_construct = SeqIO.read(sample_path,'genbank')
    seq_construct.id = 'TEMPCOPY '+in_id
    seq_list = []    
    seq_list.append(seq_construct)
    return add_samples()
        
    ''' MUSCLE SECTION
    if out_file:
        muscle_cline = MuscleCommandline(input=in_file,out=out_file)
    else: 
        muscle_cline = MuscleCommandline(input=in_file)
    stdout, stderr = muscle_cline()
    '''

def main(argv):
    '''USAGE: python sequencing_auto.py [sequencing_directory] [phred_cutoff] [minimum_length_of_read]'''
    if len(argv)<4:
        minLength = 500
        if len(argv)<3:
            phred = 0.01
            if len(argv)<2:    
                seq_dir = ''
            else:   
                seq_dir = argv[1]
        else:
            seq_dir = argv[1]
            phred = argv[2]
            phred = float(phred)
    else:
        script, seq_dir, phred, minLength = argv
        phred = float(phred)
        minLength = int(minLength)

    zips = move_downloads(seq_dir)
    key = csv.reader(open(seq_dir+'key.csv','rU'), delimiter=',')

    for i,row in enumerate(key):
        if i>0 and len(row[2])>1:
            sample_id = row[0]
            sample_path = row[2]
            if not sample_path.find('../Dropbox'):
                sample_path = '../Dropbox/' + sample_path
            parse_construct(seq_dir,sample_path,sample_id,phred,minLength)
    return str(zips)+' moved, trimmed, and associated.'

if __name__ == "__main__":
    sys.exit(main(sys.argv))


